package cn.cupk.corporateshuttlemanagesystem.controller;

import cn.cupk.corporateshuttlemanagesystem.mapper.LineInformationMapper;
import cn.cupk.corporateshuttlemanagesystem.pojo.Routes;
import cn.cupk.corporateshuttlemanagesystem.result.PageResult;
import cn.cupk.corporateshuttlemanagesystem.result.RequestParams;
import cn.cupk.corporateshuttlemanagesystem.result.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/xlxx")
@Slf4j
public class LineInformationController {

    @Autowired
    private LineInformationMapper lineInformationMapper;

    @PostMapping("/list")
    public Result<Object> page(@RequestBody RequestParams<Routes> params) {
        // 获取线路名称
        String name = null;
        if (params.getData() != null)
            name = params.getData().getName();
        Page<Object> page = PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<Routes> routes = lineInformationMapper.page(name);
        // 遍历查询结果
        for (Routes route : routes) {
            String stopsId = route.getStopsId();
            // 判断 stopsId 是否为空
            if (stopsId != null && stopsId.equals("")) {
                continue;
            }

            String[] stationName = stopsId.split("，");
            List<Integer> stationId = new ArrayList<>();
            for (String s : stationName) {
                // 将 s 转换为 Integer 类型
                stationId.add(Integer.parseInt(s.trim()));
            }
            List<String> list = lineInformationMapper.stopList(stationId);
            route.setStationName(list);
        }
        return Result.ok(new PageResult<>(page.getTotal(), routes));
    }

    @GetMapping("/order")
    public Result<Object> order(Integer routeId, String userId) {
        String s = lineInformationMapper.selectOne(routeId);
        if (s != null) {
            // 判断是否已经预约过
            String[] split = s.split("，");
            for (String s1 : split) {
                if (s1.equals(userId)) {
                    return Result.error("已经预约过了");
                }
            }
        }
        // 预约
        String order = null;
        if (s != null && !s.equals(""))
            order = s + "，" + userId;
        else
            order = userId;
        // 更新预约信息
        Integer result = lineInformationMapper.order(routeId, order);
        return Result.ok(result > 0 ? "预约成功" : "预约失败");
    }


}
